#! /usr/bin/env python
# -*- coding:utf-8 -*-
# vim:fileencoding=utf-8


import smtplib, os
from mako.template import Template
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import date


def _render_template(template_file, data):
    retval = None

    if os.path.exists(template_file):
        my_template = Template(filename = template_file, input_encoding = 'utf-8', output_encoding = 'utf-8')
        retval = my_template.render(rows = data, date_str = date.today().isoformat())

    return retval


def send_email(to_email = [], server_config={}, data=[], template_file=None):
    """Send email"""
    if to_email:

        if not isinstance(to_email, list):
            to_email = [to_email]

        try:
            smtp_server = smtplib.SMTP(server_config.get('smtp_server', 'smtp.qiye.163.com'), server_config.get('smtp_port', 25), timeout = int(server_config.get('smtp_timeout', 10)))
            smtp_server.set_debuglevel(server_config.get('level', 0))
            smtp_server.login(server_config.get('account', 'noreply@idreamsky.com'), server_config.get('password', 'noreply123'))
            from_addr, to_addr, subject = server_config.get('from_addr', 'noreply@idreamsky.com'), to_email, server_config.get('subject', 'This is test email')
            message = MIMEMultipart()
            message['From'], message['To'], message['Subject'] = from_addr, ';'.join(to_addr), subject
            _html = _render_template(template_file, data)
            message_html = MIMEText(_html, 'html', 'utf-8')
            message.attach(message_html)
            smtp_server.sendmail(from_addr, to_addr, message.as_string())
            smtp_server.quit()
        except Exception as e:
            print "Send email fail, message:%s" % str(e)
